﻿using LeSoft.Application.Bussiness;
using LeSoft.Application.Cache;
using LeSoft.Application.Code;
using LeSoft.Application.Entity;
using LeSoft.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace LeSoft.Application.Web.Areas.PropertyManage.Controllers
{
    public class CS_PollingController : MvcControllerBase
    {
        private PollingBLL bll = new PollingBLL();

        #region
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult ItemIndex()
        {
            return View();
        }
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult ItemForm()
        {
            return View();
        }
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult ItemObjectForm()
        {
            return View();
        }
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult ContentIndex()
        {
            return View();
        }
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult ContentForm()
        {
            return View();
        }
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult ContentItemForm()
        {
            return View();
        }

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult PollingSettingForm()
        {
            return View();
        }
        #endregion
        #region 项目
        public ActionResult GetItemDetailListJson(Pagination pagination, string queryJson)
        {

            var watch = CommonHelper.TimerStart();
            var data = bll.GetItemPageList(pagination, queryJson);
            var JsonData = new
            {
                rows = data,
                total = pagination.total,
                page = pagination.page,
                records = pagination.records,
                costtime = CommonHelper.TimerEnd(watch)
            };
            return Content(JsonData.ToJson());
        }
        /// 获取巡检项目树形列表
        /// </summary>
        /// <param name="keyword">ItemType Id</param>
        /// <returns>项目类别+项目</returns>   
        [HttpGet]
        public ActionResult GetItemTreeJson(string keyword)
        {
            var data = bll.GetItemList();
            var itemId = new DataItemBLL().GetEntity("PollingType", "").ItemId;
            var datacategory = !string.IsNullOrEmpty(keyword) ? new DataItemDetailBLL().GetList(keyword) : new DataItemDetailBLL().GetList(itemId);
            if (!string.IsNullOrEmpty(keyword)) data = data.Where(t => t.Type == keyword).ToList();
            var treeList = new List<TreeEntity>();
            foreach (DataItemDetailEntity item in datacategory)
            {
                TreeEntity tree = new TreeEntity();
                bool hasChildren = datacategory.Count(t => t.ParentId == item.ItemDetailId) == 0 ? false : true;
                if (hasChildren == false)
                {
                    hasChildren = datacategory.Count(t => t.ItemDetailId == item.ItemDetailId) == 0 ? false : true;
                    if (hasChildren == false)
                    {
                        continue;
                    }
                }
                tree.id = item.ItemDetailId;
                tree.text = item.ItemName;
                tree.value = item.ItemValue;
                tree.isexpand = true;
                tree.complete = true;
                tree.hasChildren = hasChildren;
                tree.parentId = "0";
                tree.title = "type";
                //tree.img = item.Icon;
                treeList.Add(tree);
            }
            if (!OperatorProvider.Provider.Current().IsSystem)
                data = data.Where(t => t.OrganizeId == OperatorProvider.Provider.Current().CompanyId).ToList();
            foreach (PollingItemEntity item in data)
            {
                TreeEntity tree = new TreeEntity();
                bool hasChildren = data.Count(t => t.ParentId == item.Id) == 0 ? false : true;
                if (hasChildren == false)
                {
                    hasChildren = data.Count(t => t.Id == item.Id) == 0 ? false : true;
                    if (hasChildren == false)
                    {
                        continue;
                    }
                }
                tree.id = item.Id;
                tree.text = item.Name;
                tree.value = item.Id;
                tree.isexpand = true;
                tree.complete = true;
                tree.hasChildren = hasChildren;
                tree.Attribute = "IsParentId";
                if (!string.IsNullOrEmpty(keyword))
                {
                    tree.parentId = "0";
                    tree.AttributeValue = "0";
                }
                else if (!string.IsNullOrEmpty(item.ParentId))
                {
                    tree.parentId = item.ParentId;
                    tree.AttributeValue = "1";
                }
                else
                {
                    tree.parentId = item.Type;
                    tree.AttributeValue = "0";
                }
                tree.title = "item";
                tree.img = null;
                treeList.Add(tree);
            }
            return Content(treeList.TreeToJson());
        }
        public ActionResult GetDetaliFormJson(string keyValue)
        {
            var data = bll.GetItemEntity(keyValue);
            return Content(data.ToJson());
        }

        public ActionResult GetRelationDeviceItemList(string queryJson, int ItemTag = 1)
        {
            var data = bll.GetRelationDeviceItemList(ItemTag, queryJson);
            List<object> objlist = new List<object>();
            foreach (var item in data)
            {
                var TypeName = new DeviceTypeBLL().GetEntity(item.DeviceTypeId).IsEmpty() ? "" : new DeviceTypeBLL().GetEntity(item.DeviceTypeId).Name;
                var dd = new DataItemCache().GetDataItemList("DeviceLevel").FirstOrDefault(e => e.ItemDetailId == item.DeviceLevel);
                var Level = dd.IsEmpty() ? "" : dd.ItemName;
                objlist.Add(new { Id = item.Id, TypeId = item.DeviceTypeId, Type = TypeName, LevelValue = item.DeviceLevel, Level = Level, OrganizeId = item.OrganizeId, ProjectType = item.ProjectType });
            }
            return Content(objlist.ToJson());
        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        public ActionResult SaveItemDetailForm(string keyValue, string BaseInfo, string ContentList, string DeviceList)
        {
            var entity = BaseInfo.ToObject<PollingItemEntity>();
            var list = ContentList.ToList<PollingContentEntity>();
            var devicelist = DeviceList.ToList<RelationDeviceItemEntity>();
            if (devicelist.Count <= 0)
                devicelist = null;
            bll.SaveIForm(keyValue, entity, devicelist, list);

            return Success("操作成功。");
        }
        /// <summary>
        /// 删除项目
        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        public ActionResult RemoveItemDetailForm(string keyValue)
        {
            bll.RemoveIForm(keyValue);
            return Success("删除成功。");
        }
        #endregion

        #region 内容
        public ActionResult GetContentListJson(Pagination pagination, string queryJson)
        {
            var watch = CommonHelper.TimerStart();
            var data = bll.GetContentPageList(pagination, queryJson);
            var org = new OrganizeCache().GetList();
            foreach (var item in data)
            {
                var model = org.FirstOrDefault(t => t.OrganizeId == item.OrganizeId);
                item.OrganizeId = model == null ? "" : model.FullName;
            }
            var JsonData = new
            {
                rows = data,
                total = pagination.total,
                page = pagination.page,
                records = pagination.records,
                costtime = CommonHelper.TimerEnd(watch)
            };
            return Content(JsonData.ToJson());
        }
        /// <summary>
        /// 获取项目内容列表
        /// </summary>
        /// <param name="Type"></param>
        /// <param name="ItemId"></param>
        /// <returns></returns>
        public ActionResult GetContentList(string queryJson)
        {
            var queryParam = queryJson.ToJObject();
            string type = !queryParam["Type"].IsEmpty() ? queryParam["Type"].ToString() : "";
            string ItemId = !queryParam["ItemId"].IsEmpty() ? queryParam["ItemId"].ToString() : "";
            var relationdata = bll.GetRelationContentList(type, ItemId).ToList();
            var contentdata = bll.GetContentList().Where(t => t.Type == type || t.Type.IsEmpty()).ToList();
            if (!queryParam["condition"].IsEmpty() && !queryParam["keyword"].IsEmpty())
            {
                string condition = queryParam["condition"].ToString();
                string keyword = queryParam["keyword"].ToString();
                #region 多条件查询
                switch (condition)
                {
                    case "Code":    //编号
                        contentdata = contentdata.Where(t => t.Code.Contains(keyword)).ToList();
                        break;
                    case "Name":      //名称
                        contentdata = contentdata.Where(t => t.Name.Contains(keyword)).ToList();
                        break;

                }
                #endregion
            }
            if (relationdata != null && relationdata.Count() > 0)
            {
                var data = from a in relationdata
                           join b in contentdata on a.ContentId equals b.Id
                           select new
                           {
                               a.Type,
                               a.TypeName,
                               a.ItemId,
                               b.Id,
                               b.Code,
                               b.Name,
                               b.Criterion,
                               b.CheckWay,
                               b.IsNeed,
                               b.Category,
                               b.Memo,
                               b.TypeDescription
                           };
                return Content(data.ToJson());
            }
            else
                return null;
        }
        /// <summary>
        /// 获取巡检内容树带checkbox
        /// </summary>
        /// <param name="Type">巡检专业</param>
        /// <param name="ItemId">巡检项目</param>
        /// <returns></returns>
        public ActionResult GetContentTreeJson(string Type, string ItemId)
        {
            var data = bll.GetContentList().Where(t => t.Type == Type || t.Type.IsEmpty()).ToList();
            var relationdata = bll.GetRelationContentList(Type, ItemId).ToList();
            var treeList = new List<TreeEntity>();
            string guid = Guid.NewGuid().ToString();
            //  int chState = 0; if (data.Count() == relationdata.Count()) chState = 1;
            treeList.Add(new TreeEntity() { id = guid, value = guid, text = "所有巡检内容", parentId = "0", showcheck = false, hasChildren = true, isexpand = true, complete = true });
            foreach (PollingContentEntity item in data)
            {
                TreeEntity tree = new TreeEntity();
                bool hasChildren = data.Count(t => t.ParentId == item.Id) == 0 ? false : true;
                tree.id = item.Id;
                tree.text = item.Name;
                tree.value = item.Id;
                tree.showcheck = true;
                tree.checkstate = relationdata.Count(t => t.ContentId == item.Id);
                tree.isexpand = true;
                tree.complete = true;
                tree.hasChildren = hasChildren;
                tree.parentId = string.IsNullOrEmpty(item.ParentId) ? guid : item.ParentId;
                tree.img = null;
                treeList.Add(tree);
            }
            return Content(treeList.TreeToJson());
        }
        public ActionResult GetContentJson(string keyValue)
        {
            var data = bll.GetContentEntity(keyValue);
            return Content(data.ToJson());
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        [HandlerAction(OperationType.Create, "保存巡检内容", "SaveContentForm")]
        public ActionResult SaveContentForm(string keyValue, PollingContentEntity pollingContentEntity)
        {
            try
            {
                bll.SaveCForm(keyValue, pollingContentEntity);
                return Success("操作成功。");
            }
            catch (Exception e)
            {
                return Error(e.Message);
            }
        }
        /// <summary>
        /// 删除内容
        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        public ActionResult RemoveContentForm(string keyValue)
        {
            bll.RemoveCForm(keyValue);
            return Success("删除成功。");
        }
        #endregion

        #region 巡检对象
        /// <summary>
        /// 获取商铺巡检对象列表
        /// </summary>
        /// <param name="itemcode"></param>
        /// <param name="parentid"></param>
        /// <param name="condition"></param>
        /// <param name="keyword"></param>
        /// <returns></returns>
        public ActionResult GetRoomRelationOIListJson(string ItemId, string TypeId, string organizeid)
        {
            var Objlist =new PStructCache().GetList().Where(t => t.Type == 5);
            if (!string.IsNullOrEmpty(organizeid))
            {
                Objlist = Objlist.Where(t => t.OrganizeId == organizeid).ToList();
            }
            var list = new PollingRelationOIBLL().GetList("", ItemId, TypeId);
            var data = (from a in Objlist
                        join b in list on a.Id equals b.ObjectId
                        into ab
                        from b in ab.DefaultIfEmpty()
                        select new
                        {
                            ObjectId = a.Id,
                            ObjName = a.Name,
                            OrganizeId = a.OrganizeId,
                            Address = a.AllName,
                            ObjCode = a.Code,
                            Frequency = b != null ? b.Frenquency : 0,
                            isCheck = b != null ? true : false,
                            OIId = b != null ? b.Id : ""
                        }).ToList();
            return Content(data.ToJson());
        }

        /// <summary>
        /// 获取公共区域巡检对象列表
        /// </summary>
        /// <param name="itemcode"></param>
        /// <param name="parentid"></param>
        /// <param name="condition"></param>
        /// <param name="keyword"></param>
        /// <returns></returns>
        public ActionResult GetAreaRelationOIListJson(string ItemId, string TypeId, string organizeid)
        {
            var Objlist = bll.GetList();
            if (!string.IsNullOrEmpty(organizeid))
            {
                Objlist = Objlist.Where(t => t.OrganizeId == organizeid).ToList();
            }
            var list = new PollingRelationOIBLL().GetList("", ItemId, TypeId);
            var data = (from a in Objlist
                        join b in list on a.PCode equals b.ObjectId
                        into ab
                        from b in ab.DefaultIfEmpty()
                        select new
                        {
                            ObjectId = a.PCode,
                            ObjName = a.Name,
                            ObjCode = a.EnCode,
                            a.FlagWay,
                            a.OrganizeId,
                            Address = a.PSAllName,
                            Frequency = b != null ? b.Frenquency : 0,
                            isCheck = b != null ? true : false,
                            OIId = b != null ? b.Id : ""
                        }).ToList();
            return Content(data.ToJson());
        }

        /// <summary>
        /// 获取巡检项目列表--公区关联项目
        /// </summary>
        /// <param name="itemcode"></param>
        /// <param name="parentid"></param>
        /// <param name="condition"></param>
        /// <param name="keyword"></param>
        /// <returns></returns>
        public ActionResult GetItemRelationOIListJson(string ObjectId, string TypeId, string OrganizeId)
        {
            var itemlist = bll.GetItemList("", "", TypeId);
            if (!string.IsNullOrEmpty(OrganizeId))
                itemlist = itemlist.Where(t => itemlist.Count(a => a.ParentId == t.Id) == 0 && t.OrganizeId == OrganizeId).ToList();
            else
                itemlist = itemlist.Where(t => itemlist.Count(a => a.ParentId == t.Id) == 0).ToList();
            var list = new PollingRelationOIBLL().GetList(ObjectId, "", TypeId);
            var data = (from a in itemlist
                        join b in list on a.Id equals b.ItemId
                        into ab
                        from b in ab.DefaultIfEmpty()
                        select new
                        {
                            a.Id,
                            a.TypeName,
                            a.Unit,
                            a.UnitNum,
                            a.Name,
                            a.Frenquency,
                            a.Code,
                            a.Type,
                            isCheck = b != null ? true : false,
                            Frequency = b != null ? b.Frenquency : 0,
                            OIId = b != null ? b.Id : ""
                        }).ToList();
            return Content(data.ToJson());
        }

        /// <summary>
        /// 保存关联巡检项目
        /// </summary> 
        /// <param name="keyValue"></param>
        /// <param name="pollingItemEntity"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        public ActionResult SaveRelationOIForm(string objlist, string ids)
        {
            var list = objlist.ToList<PollingRelationOIEntity>();
            new PollingRelationOIBLL().SaveForm(list, ids);
            return Success("操作成功。");
        }
        #endregion
    }
}
